package com.help10000.rms.ui.fragments

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewTreeObserver
import android.widget.CheckBox
import androidx.fragment.app.Fragment
import com.amir.common.api.ApiContents
import com.amir.common.api.download.LoginPageEvent
import com.amir.common.beans.AppVersionInfo
import com.amir.common.beans.AppVersionInfoEntity
import com.amir.common.beans.CompanyEntity
import com.amir.common.utils.AppVersionUtils
import com.amir.common.utils.ButtonUtils
import com.amir.common.utils.Constant
import com.amir.common.utils.IMEUtil
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.presenter.AppVersionInfoPresenter
import com.help10000.rms.mvp.presenter.CompanyListPresenter
import com.help10000.rms.mvp.presenter.LoginPresenter
import com.help10000.rms.mvp.presenter.SelectCompanyPresenter
import com.help10000.rms.mvp.view.CommonView
import com.help10000.rms.mvp.view.CompanyListView
import com.help10000.rms.mvp.view.LoginView
import com.help10000.rms.mvp.view.SelectCompanyView
import com.help10000.rms.ui.activitys.BindEmployeeActivity
import com.help10000.rms.ui.activitys.MainActivity
import com.help10000.rms.ui.activitys.OpenUrlActivity
import com.help10000.rms.ui.activitys.SelectCompanyActivity
import com.help10000.rms.ui.activitys.logins.ForgetPwdActivity
import com.help10000.rms.ui.activitys.logins.RegisterActivity
import com.help10000.rms.ui.activitys.mine.AppVersionInfoActivity
import com.help10000.rms.ui.base.BaseFragment
import com.help10000.rms.ui.dialog.PrivacyRemainderDialog
import com.help10000.rms.ui.utils.EventBusHelper
import com.help10000.rms.ui.utils.PageUtils
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_login.btn_login
import kotlinx.android.synthetic.main.fragment_login.et_code
import kotlinx.android.synthetic.main.fragment_login.et_phone
import kotlinx.android.synthetic.main.fragment_login.et_pwd
import kotlinx.android.synthetic.main.fragment_login.ll_pwdlogin
import kotlinx.android.synthetic.main.fragment_login.ll_smslogin
import kotlinx.android.synthetic.main.fragment_login.ruleCheckState
import kotlinx.android.synthetic.main.fragment_login.ruleLayout
import kotlinx.android.synthetic.main.fragment_login.tv_forget
import kotlinx.android.synthetic.main.fragment_login.tv_goRegister
import kotlinx.android.synthetic.main.fragment_login.tv_loginType
import kotlinx.android.synthetic.main.fragment_login.tv_sendsms
import kotlinx.android.synthetic.main.fragment_login.tv_userPrivacy
import kotlinx.android.synthetic.main.fragment_login.tv_userRule
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LoginFragment() : BaseFragment<LoginPresenter, LoginView>(),
    View.OnClickListener, CommonView<AppVersionInfoEntity>,
    LoginView, SelectCompanyView, CompanyListView,
    SharedPreferences.OnSharedPreferenceChangeListener {

    var autoLogin = false
    var pushContent: String? = null
    var pwdLogin = false
    private lateinit var ruleCheckState: CheckBox
    private var listener: ((Boolean) -> Unit)? = null
    // 获取SPUtils内部的SharedPreferences实例
    private val sp: SharedPreferences? by lazy {
        if (isAdded) SPUtils.instance(requireContext()) else null
    }

    companion object {
        fun newInstance(reload: Boolean, push: String?, isPwd: Boolean?): LoginFragment {
            val bundle = Bundle()
            bundle.putBoolean("reload", reload)
            isPwd?.let { bundle.putBoolean("is_pwd", it) }
            bundle.putString("push_content", push)
            val fragment = LoginFragment()
            fragment.arguments = bundle
            return fragment
        }
        var checkBoxState: Boolean = false // 默认未勾选
        val stateListeners = mutableListOf<(Boolean) -> Unit>()
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ruleCheckState = view.findViewById(R.id.ruleCheckState)

        // 初始化SPUtils确保实例已创建
        if (isAdded) {
            SPUtils.instance(requireContext())
        }

        // 从SP读取初始状态
        checkBoxState = SPUtils.getBoolean("read_privacy")
        ruleCheckState.isChecked = checkBoxState

        // 注册SP变化监听器
        sp?.registerOnSharedPreferenceChangeListener(this)

        val localListener: (Boolean) -> Unit = { isChecked ->
            if (isAdded && view != null) {
                ruleCheckState.isChecked = isChecked
            }
        }
        listener = localListener
        stateListeners.add(localListener)

        // 复选框状态变化时同步到SP
        ruleCheckState.setOnCheckedChangeListener { _, isChecked ->
            checkBoxState = isChecked
            SPUtils.save("read_privacy", isChecked)
            stateListeners.forEach { it.invoke(isChecked) }
        }
    }

    // SP值变化时自动更新复选框（确保主线程更新UI）
    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        if (key == "read_privacy" && sharedPreferences != null) {
            // 使用post确保在主线程更新UI
            ruleCheckState.post {
                if (isAdded) {
                    val newValue = SPUtils.getBoolean("read_privacy")
                    if (checkBoxState != newValue) {
                        checkBoxState = newValue
                        ruleCheckState.isChecked = newValue
                        stateListeners.forEach { it.invoke(newValue) }
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 刷新状态确保同步
        if (isAdded) {
            val readPrivacy = SPUtils.getBoolean("read_privacy")
            if (ruleCheckState.isChecked != readPrivacy) {
                ruleCheckState.isChecked = readPrivacy
                checkBoxState = readPrivacy
            }
        }
    }

    override fun getlayoutId(): Int {
        return R.layout.fragment_login
    }

    override fun initView(rootView: View?) {
        // 初始化视图代码
    }

    override fun initData(savedInstanceState: Bundle?) {
        pushContent = arguments?.getString("push_content")
        this.pwdLogin = arguments?.getBoolean("is_pwd", false) == true

        if (isAdded) {
            val accoun = SPUtils.getString(Constant.accoun)
            et_phone.setText(accoun)
        }

        if (this.pwdLogin) {
            tv_forget.visibility = View.VISIBLE
            et_phone.hint = "通行证ID/手机号码/邮箱"
            ll_pwdlogin.visibility = View.VISIBLE
            ll_smslogin.visibility = View.GONE
        } else {
            tv_forget.visibility = View.GONE
            et_phone.hint = "手机号码"
            ll_pwdlogin.visibility = View.GONE
            ll_smslogin.visibility = View.VISIBLE
            // 重置发送按钮
            mCountDownTimer?.cancel()
            tv_sendsms.text = "发送验证码"
            tv_sendsms.isEnabled = true
        }

        if (!this.pwdLogin) {
            // 延迟到视图加载完成后发起请求
            view?.viewTreeObserver?.addOnGlobalLayoutListener(object :
                ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    // 移除监听器避免重复调用
                    view?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                    // 发起版本检查
                    if (isAdded) {
                        val checkUpdate = AppVersionInfoPresenter(this@LoginFragment)
                        checkUpdate.checkUpdate()
                    }
                }
            })
        }
    }

    override fun initListener() {
        et_phone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length == 0)
                    et_pwd.setText(null)
            }
            override fun afterTextChanged(s: Editable?) {}
        })

        tv_forget.setOnClickListener(DuplicateClickProxy(this))
        btn_login.setOnClickListener(DuplicateClickProxy(this))
        tv_sendsms.setOnClickListener(DuplicateClickProxy(this))
        tv_loginType.setOnClickListener(DuplicateClickProxy(this))
        tv_userPrivacy.setOnClickListener(DuplicateClickProxy(this))
        tv_userRule.setOnClickListener(DuplicateClickProxy(this))
        tv_goRegister.setOnClickListener(DuplicateClickProxy(this))
        ruleLayout.setOnClickListener(DuplicateClickProxy(this))

        EventBusHelper.register(this)
    }

    // 修复核心：强化空安全检查
    private fun setLoginButtonEnabled(enabled: Boolean) {
        // 三重检查：Fragment存活 + 视图存在 + 按钮不为null
        if (isAdded && view != null && btn_login != null) {
            btn_login.isEnabled = enabled // 控制点击响应
            // 根据状态设置背景
            val backgroundRes = if (enabled) {
                R.drawable.shape_login_button // 正常可点击背景
            } else {
                R.drawable.shape_login_button_pressed // 禁止点击背景（灰色/按压态）
            }
            btn_login.setBackgroundResource(backgroundRes)
        }
    }

    override fun onClick(v: View?) {
        // 基础检查：确保Fragment处于活跃状态
        if (!isAdded || view == null) return

        when (v?.id) {
            R.id.ruleLayout -> {
                ruleCheckState.isChecked = !ruleCheckState.isChecked
            }
            R.id.tv_forget -> {
                PageUtils.jumpToActivity(requireActivity(), ForgetPwdActivity::class.java)
            }
            R.id.tv_sendsms -> {
                // 安全调用：检查按钮是否存在
                btn_login?.setBackgroundResource(R.drawable.shape_login_button)
                if (!ButtonUtils.isFastDoubleClick(R.id.tv_sendsms) &&
                    (tv_sendsms.text == "重新发送" || tv_sendsms.text == "发送验证码")) {
                    // 关键：点击发送验证码前，先取消旧的倒计时任务
                    mCountDownTimer?.cancel() // 清除旧任务
                    mCountDownTimer = null // 置空避免残留引用
                    tv_sendsms.isEnabled = false // 禁用按钮避免重复点击
                    mPresenter.sendSms(et_phone.text.toString())
                }
            }
            R.id.btn_login -> {
                errorEccor = false
                IMEUtil.hideIME(requireContext(), et_pwd) // 先隐藏输入法
                // 统一设置登录按钮为"加载中"背景（点击后立即切换）
                setLoginButtonEnabled(false)

                if (!ruleCheckState.isChecked) {
                    // 确保Fragment仍附着在Activity上
                    if (!requireActivity().isFinishing) {
                        // 自动勾选协议（会触发SP保存）
                        ruleCheckState.isChecked = true
                        // 执行登录逻辑（根据登录类型选择对应方法）
                        Handler(Looper.getMainLooper()).postDelayed({
                            if (pwdLogin) {
                                mPresenter.login(et_phone, et_pwd)
                            } else {
                                mPresenter.loginByValidCode(
                                    et_phone.text.toString().trim(),
                                    et_code.text.toString().trim()
                                )
                            }
                        }, 1150)
                    } else {
                        // 若Activity已销毁，恢复按钮背景
                        setLoginButtonEnabled(true)
                    }
                    return
                }

                // 已勾选隐私协议：直接执行登录
                if (pwdLogin) {
                    mPresenter.login(et_phone, et_pwd)
                } else {
                    mPresenter.loginByValidCode(
                        et_phone.text.toString().trim(),
                        et_code.text.toString().trim()
                    )
                }
            }
            R.id.tv_loginType -> {
                btn_login?.setBackgroundResource(R.drawable.shape_login_button)
                if (ll_pwdlogin.visibility == View.GONE) {
                    tv_loginType.text = "使用短信登陆"
                    ll_pwdlogin.visibility = View.VISIBLE
                    ll_smslogin.visibility = View.GONE
                } else {
                    tv_loginType.text = "使用账号密码登陆"
                    ll_pwdlogin.visibility = View.GONE
                    ll_smslogin.visibility = View.VISIBLE
                }
            }
            R.id.tv_goRegister -> {
                PageUtils.jumpToActivity(requireActivity(), RegisterActivity::class.java)
            }
            R.id.tv_userRule -> {
                OpenUrlActivity.startActivity(requireActivity(), ApiContents.UserRuleUrl)
            }
            R.id.tv_userPrivacy -> {
                OpenUrlActivity.startActivity(requireActivity(), ApiContents.UserPrivacyUrl)
            }
        }
    }

    var mCountDownTimer: CountDownTimer? = null
    override fun sendSmsSuccess() {
        // 取消旧的倒计时（避免内存泄漏）
        mCountDownTimer?.cancel()
        mCountDownTimer = object : CountDownTimer(30 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                // 检查Fragment状态
                if (isAdded && tv_sendsms != null) {
                    tv_sendsms.text = "${millisUntilFinished / 1000}s后重发"
                }
            }
            override fun onFinish() {
                // 检查Fragment状态
                if (isAdded && tv_sendsms != null) {
                    tv_sendsms.text = "重新发送"
                    tv_sendsms.isEnabled = true
                }
            }
        }.start()
        dismissLoading() // 关闭全局加载动画
    }

    override fun checkSMSSuccess() {}

    override fun loginSuccess() {
        // 安全检查后再操作控件
        if (isAdded && btn_login != null) {
            btn_login.setBackgroundResource(R.drawable.shape_login_button)
        }

        if (!globalData.deviceId.isNullOrEmpty()) {
            mPresenter.bindDeviceId(globalData.deviceId!!)
        }

        companyListPresenter = CompanyListPresenter(this)
        companyListPresenter?.companyList()
        // 清理验证码按钮状态
        mCountDownTimer?.cancel()
        if (isAdded && tv_sendsms != null) {
            tv_sendsms.text = "发送验证码"
            tv_sendsms.isEnabled = true
        }
    }

    var companyListPresenter: CompanyListPresenter? = null
    var selectCompanyPresenter: SelectCompanyPresenter = SelectCompanyPresenter(this)
    override fun companyListData(t: CompanyEntity) {
        if (!isAdded) return // 检查Fragment状态

        if (t.data.CmpyList.size == 1) {
            selectCompanyPresenter.companyLogin(t.data.CmpyList[0])
        } else if (t.data.CmpyList.size > 1) {
            isLogined = true
            if (autoLogin) {
                val cmpyCode = SPUtils.getString(Constant.CmpyCode)
                var found = false
                if (!cmpyCode.isNullOrEmpty()) {
                    for (cmpy in t.data.CmpyList) {
                        if (cmpy.CmpyCode == cmpyCode) {
                            found = true
                            selectCompanyPresenter.companyLogin(cmpy)
                            break
                        }
                    }
                    if (found) {
                        return
                    }
                }
            }
            val intent = Intent(requireActivity(), SelectCompanyActivity::class.java)
            intent.putExtra("data", t.data)
            startActivity(intent)
        } else {
            isLogined = true
            startActivity(Intent(requireActivity(), BindEmployeeActivity::class.java))
        }
    }


    override fun companyLoginSuccess() {
        isLogined = true
        if (isAdded) {
            val intent = Intent(requireActivity(), MainActivity::class.java)
            intent.putExtra("push_content", pushContent)
            startActivity(intent)
            requireActivity().finish()
        }
    }

    override fun onDestroy() {
        // 清理倒计时器
        mCountDownTimer?.cancel()
        mCountDownTimer = null
        // 取消事件订阅
        EventBusHelper.unRegister(this)
        // 注销SP监听器
        sp?.unregisterOnSharedPreferenceChangeListener(this)
        // 清理Presenter
        companyListPresenter?.detachView()
        selectCompanyPresenter.detachView()
        super.onDestroy()
    }

    var errorEccor: Boolean = false
    var isLogined: Boolean = false

    override fun onError(mess: String?) {
        if(isAdded) {
            setLoginButtonEnabled(true)
            super.onError(mess)
            errorEccor = true
            autoLogin = false
            // 恢复发送验证码按钮状态
            mCountDownTimer?.cancel() // 取消可能的倒计时
            if (tv_sendsms != null) {
                tv_sendsms.text = "发送验证码"
                tv_sendsms.isEnabled = true
            }
        }
    }

    override fun onShow(){
        setLoginButtonEnabled(true)
    }

    override fun showDialog(mess: String?, code: Int) {
        if (isAdded && !requireActivity().isFinishing && !requireActivity().isDestroyed) {
            super.showDialog(mess, code)
            SPUtils.remove(Constant.pwd)
            et_pwd.text = null
            errorEccor = true
            autoLogin = false
            dismissLoading()
        }
    }

    override fun dismissLoading() {
        // 安全调用
        if (isAdded && tv_sendsms != null) {
            tv_sendsms.isEnabled = true
        }
        setLoginButtonEnabled(true)
        super.dismissLoading()
    }

    override fun createPresenter(): LoginPresenter {
        return LoginPresenter(this)
    }

    override fun registerSucc() {}


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginPageEvent(loginPageEvent: LoginPageEvent) {
        if (isAdded && !loginPageEvent.pwd.isNullOrBlank()) {
            et_phone.setText(loginPageEvent.account)
            et_pwd.setText(loginPageEvent.pwd)
            mPresenter.login(et_phone, et_pwd)
        }
    }

    override fun onDestroyView() {
        // 修复：移除对val控件的重新赋值，改为清理监听器和Presenter
        stateListeners.remove(listener)
        listener = null
        companyListPresenter?.detachView()
        selectCompanyPresenter.detachView()
        super.onDestroyView()
    }

    private var data: AppVersionInfo? = null
    override fun onDataSuccess(appVersionInfo: AppVersionInfoEntity) {
        if (!isAdded || requireActivity().isFinishing) {
            return
        }

        this.data = appVersionInfo.data?.AppVersionInfo
        val version = AppVersionUtils.getAppVersionName(requireContext())
        val localData = data
        val localVersion = version

        if (localData != null && localVersion != null) {
            val needUpdate = AppVersionUtils.compareVersion(localData.Version.toString(), localVersion) ?: false
            if (needUpdate) {
                errorEccor = true
                XPopup.Builder(requireActivity())
                    .asConfirm(
                        "版本更新", "检测到新版本，是否前往更新?",
                        {
                            PageUtils.jumpToActivity(requireActivity(), AppVersionInfoActivity::class.java)
                        }, {
                            val accountName = SPUtils.getString(Constant.accountName)
                            val encodePassword = SPUtils.getString(Constant.encodePassword)
                            if (!accountName.isNullOrEmpty() && !encodePassword.isNullOrEmpty()) {
                                errorEccor = false
                                autoLogin = true
                                mPresenter.autoLogin(SPUtils.getString(Constant.nonceStr), encodePassword, accountName)
                            }
                        }).show()
            } else {
                val accountName = SPUtils.getString(Constant.accountName)
                val encodePassword = SPUtils.getString(Constant.encodePassword)
                if (!accountName.isNullOrEmpty() && !encodePassword.isNullOrEmpty()) {
                    autoLogin = true
                    mPresenter.autoLogin(SPUtils.getString(Constant.nonceStr), encodePassword, accountName)
                } else {
                    this.dismissLoading()
                    errorEccor = true
                }
            }
        } else {
            this.dismissLoading()
            errorEccor = true
        }
    }
}
